<?php

/**
 * 供应商管理
 * @author cjli
 *
 */
class SuppliersAction extends AdminAction
{
    public function _initialize()
    {
        parent::_initialize();
    }

    //供应商列表
    public function suppliers_list()
    {

        $post = $_REQUEST;
        $where = array();

        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }

        //order by
        if (isset($_REQUEST['sort_by']) && $_REQUEST['sort_by']) {
            $sort_by = $_REQUEST['sort_by'];
        } else {
            $sort_by = 'DESC';
        }

        if (isset($_REQUEST['order_by']) && $_REQUEST['order_by']) {
            $order_by = $_REQUEST['order_by'];
        } else {
            $order_by = 'suppliers_id';
        }

        //搜索关键词
        if (isset($post['keyword']) && $post['keyword']) {
            if ($post['searchtype'] == 1) {
                $where['suppliers_name'] = array('like', '%' . $post['keyword'] . '%');
            } else if ($post['searchtype'] == 2) {
                $where['suppliers_id'] = $post['keyword'];
            } else if ($post['searchtype'] == 3) {
                $where['brand'] = $post['keyword'];
            } else if ($post['searchtype'] == 4) {
                if($post['keyword']=="净色"){
                    $where['figure'] = '0';
                }else if($post["keyword"]=="格子"){
                    $where['figure'] = '1';
                }else if($post['keyword']=="条纹"){
                    $where['figure'] = '2';
                }
            }
            $this->assign('searchtype', $post['searchtype']);
            $this->assign('searchkeyword', $post['keyword']);
        }

        if (isset($post['suppliers_type']) && $post['suppliers_type']) {
            if ($post['suppliers_type'] == 1) {
                $where['suppliers_type'] = '1';
            } else if ($post['suppliers_type'] == 2) {
                $where['suppliers_type'] = 2;
            }
            $this->assign('suppliers_type', $post['suppliers_type']);
        }
        $supplier_db = D('suppliers');
        $supplier_db->where($where);
        $count = $supplier_db->count();
        import("ORG.Util.Page");
        $Page = new Page($count, $pageRows);
        $pageShow = $Page->show();
        $this->assign('pageShow', $pageShow);
        $nowPage = $Page->getNowPageUrl();//当前页url
        //如果是post过来的则跳转到带参数的url
        if ($_POST) {
            redirect($nowPage);
            exit;
        }
        //保存当前url
        cookie('suppliers_list_nowPage', $nowPage);

        $supplier_db->where($where);
        $supplier_db->limit($Page->firstRow . ',' . $Page->listRows);
        $supplier_db->order($order_by . ' ' . $sort_by);
        $supplierList = $supplier_db->select();

        foreach ($supplierList as $key => $val) {
            $supplierList[$key]['surplus'] = SuppliersModel::inventorySurplus(0, $val['suppliers_id']);
            $supplierList[$key]['decreaseAmount'] = SuppliersModel::inventoryDecrease(0, $val['suppliers_id']);
            $supplierList[$key]['order_count'] = D('inventory')->where(array('type' => 0, 'tid' => $val['suppliers_id'], 'order_item_id' => array('gt', 0)))->count();
        }

        //预警
        //根据不同的面料类型  得到不同警告节点
        if ($post['suppliers_type'] == 1) {
            $surplus_node = 30;
            $surplus_where = "suppliers_type=1";
        } else if ($post['suppliers_type'] == 2) {
            $surplus_node = 20;
            $surplus_where = "suppliers_type=2";
        }else{
            $surplus_node = 30;
            $surplus_where = "";
        }
        $surplusTips = array();
        $supplierListYJ = $supplier_db->where($surplus_where)->order('suppliers_id desc')->select();
        foreach ($supplierListYJ as $key => $val) {
            //已全部下架的面料不予显示
            $isDisplay = D('product')->where(array('suppliers_id' => $val['suppliers_id'], 'display' => 1))->count();
            if (!$isDisplay) continue;

            $surplus = SuppliersModel::inventorySurplus(0, $val['suppliers_id']);
            if ($surplus < $surplus_node) {
                $val['surplus'] = SuppliersModel::inventorySurplus(0, $val['suppliers_id']);
                if ($surplus == 0) {
                    //查询是否有上架状态的使用相同面料id的产品,没有的话不预警
                    $count = D('product')->where(array('suppliers_id' => $val['suppliers_id'], 'display' => 1))->count();
                    if ($count == 0) continue;
                }
                $surplusTips[] = $val;
            }
        }
        $this->assign('surplusTips', $surplusTips);

        $this->assign('supplierList', $supplierList);
        $this->assign('sort_by', $sort_by);
        $this->assign('order_by', $order_by);
        $this->display('suppliers_list');
    }

    //添加供应商
    public function suppliers_add()
    {
        if ($_POST['dosubmit']) {
            $post = $_POST;
            $suppliers_id = SuppliersModel::updateSuppliersInfo($post);
            if ($suppliers_id) {
                SuppliersModel::updateSuppliersAdmin($post['admins'], $suppliers_id);
                $this->success('操作成功', U('suppliers/suppliers_list'));
            } else {
                $this->error('操作失败', U('suppliers/suppliers_list'));
            }
        } else {
            $admindb = D('admin');
            $adminList = $admindb->field("username,id,CASE WHEN suppliers_id = 0 THEN 'free' ELSE 'other' END AS 'type'")->select();
//	 			echo $admindb->getLastSql();exit;
            $this->assign('adminList', $adminList);
            $suppliers_type = $_GET['suppliers_type'];
            $this->assign('suppliers_type', $suppliers_type);
            $this->display('suppliers_form');
        }
    }

    //编辑供应商
    public function suppliers_edit()
    {
        $suppliers_id = intval($_GET['sid']);
        $suppliersInfo = SuppliersModel::getSuppliersInfo($suppliers_id);
        //var_dump($suppliersInfo);die;
        if (!$suppliersInfo) {
            $this->error('该供应商不存在', U('suppliers/suppliers_list'));
        }
        if ($_POST['dosubmit']) {
            $post = $_POST;
            $suppliers_id = SuppliersModel::updateSuppliersInfo($post, $suppliers_id);
            if ($suppliers_id) {
                SuppliersModel::updateSuppliersAdmin($post['admins'], $suppliers_id);
                $this->success('操作成功', U('suppliers/suppliers_list'));
            } else {
                $this->error('操作失败', U('suppliers/suppliers_list'));
            }
        } else {
            $admindb = D('admin');
            $adminList = $admindb->field("username,id,CASE WHEN suppliers_id = " . $suppliers_id . " THEN 'this' WHEN suppliers_id = 0 THEN 'free' ELSE 'other' END AS 'type'")->select();
            $this->assign('supplierInfo', $suppliersInfo);
            $this->assign('adminList', $adminList);
            $this->display('suppliers_form');
        }
    }

    public function suppliers_delete()
    {
        $suppliers_id = intval($_GET['sid']);
        $suppliersInfo = SuppliersModel::getSuppliersInfo($suppliers_id);
        if (!$suppliersInfo) {
            $this->error('该供应商不存在', U('suppliers/suppliers_list'));
        }
        SuppliersModel::deleteSuppliersInfo($suppliers_id);
        $this->success('操作成功', U('suppliers/suppliers_list'));
    }

    //ajax验证供应商名称
    public function suppliers_checkname_ajx()
    {
        $supplier_db = D('suppliers');
        $suppliers_id = intval($_GET['sid']);
        $suppliers_name = trim($_GET['suppliers_name']);

        if ($suppliers_id) {
            $where['suppliers_id'] = array('neq', $suppliers_id);
        }

        $where['suppliers_name'] = $suppliers_name;

        $count = $supplier_db->where($where)->count();
        if ($count) {
            echo(0);
        } else {
            echo(1);
        }

    }

    //库存记录
    public function inventory()
    {
        $where = array();
        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }

        //order by
        if (isset($_REQUEST['sort_by']) && $_REQUEST['sort_by']) {
            $sort_by = $_REQUEST['sort_by'];
        } else {
            $sort_by = 'DESC';
        }

        if (isset($_REQUEST['order_by']) && $_REQUEST['order_by']) {
            $order_by = $_REQUEST['order_by'];
        } else {
            $order_by = 'id';
        }
        $post = $_REQUEST;
        if ($post['start_time'] && $post['end_time']) {
            $start_time = strtotime($post['start_time']);
            $end_time = strtotime($post['end_time']);
            $where['recordTime'] = array(array('egt', $start_time), array('lt', $end_time), 'and');
        } else {
            if ($post['start_time']) {
                $start_time = strtotime($post['start_time']);
                $where['recordTime'] = array('egt', $start_time);
            }
            if ($post['end_time']) {
                $end_time = strtotime($post['end_time']);
                $where['recordTime'] = array('lt', $end_time);
            }
        }
        $this->assign('start_time', $post['start_time']);
        $this->assign('end_time', $post['end_time']);
        $type = intval($_REQUEST['type']);
        $tid = intval($_REQUEST['tid']);
        if(!empty($type)){
            $where['type'] = $type;
        }
        if(!empty($tid)){
            $where['tid'] = $tid;
        }

        $this->assign('type', $type);
        $this->assign('tid', $tid);

        $inventory_db = D('inventory');
        $count = $inventory_db->where($where)->count();
        if(!isset($post['action']) || $post['action']!="export") {
            import("ORG.Util.Page");
            $Page = new Page($count, $pageRows);
            $pageShow = $Page->show();
            $this->assign('pageShow', $pageShow);

            $inventory_db->limit($Page->firstRow . ',' . $Page->listRows);
        }
        $inventory_db->order($order_by . ' ' . $sort_by);
        $inventory_db->where($where);
        $inventoryList = $inventory_db->select();



        //面料 里布
        if ($type < 2) {
            if ($type == 0) {
                $suppliers = D('suppliers')->where(array('suppliers_id' => $tid))->find();
            } else {
                $suppliers = D('lining')->where(array('lining_id' => $tid))->find();
            }
            $increaseAmount = $inventory_db->where(array('type' => $type, 'tid' => $tid, 'change' => 1))
                ->getField('sum(amount)');
            $suppliers['increaseAmount'] = floatval($increaseAmount);
            $decreaseAmount = SuppliersModel::inventoryDecrease($type, $tid);

            $suppliers['decreaseAmount'] = floatval($decreaseAmount);
            $this->assign('suppliers', $suppliers);
        }
        //配饰
        if ($type == 2) {
            $product_info = D('product')->where(array('id' => $tid))->find();
            $increaseAmount = $inventory_db->where(array('type' => $type, 'tid' => $tid, 'change' => 1))
                ->getField('sum(amount)');
            $product_info['increaseAmount'] = floatval($increaseAmount);
            $decreaseAmount = SuppliersModel::inventoryDecrease($type, $tid);

            $product_info['decreaseAmount'] = floatval($decreaseAmount);
            $this->assign('product_info', $product_info);
        }

        foreach ($inventoryList as $key => $val) {
            $order = D('orders')->where(array('id' => $val['order_id']))->find();
            if ($order) $inventoryList[$key]['orderTime'] = $order['start_time'];
            $inventoryList[$key]['suppliers_name'] = $suppliers['suppliers_name'];
        }
        if(isset($post['action']) && $post['action']=="export"){
            $this->inventory_excel($inventoryList);
            exit;
        }

        $this->assign('inventoryList', $inventoryList);
        $this->assign('sort_by', $sort_by);
        $this->assign('order_by', $order_by);
        $this->display('inventory_list');
    }
    //库存统计
    public function suppliers_stats()
    {
        $where = array();
        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }

        //order by
        if (isset($_REQUEST['sort_by']) && $_REQUEST['sort_by']) {
            $sort_by = $_REQUEST['sort_by'];
        } else {
            $sort_by = 'DESC';
        }

        if (isset($_REQUEST['order_by']) && $_REQUEST['order_by']) {
            $order_by = $_REQUEST['order_by'];
        } else {
            $order_by = 'id';
        }
        $post = $_REQUEST;
        if(isset($_REQUEST['type'])){
            $type = $_REQUEST['type'];
        }else{
            $type = 0;
        }


        $this->assign('start_time', $post['start_time']);
        $this->assign('end_time', $post['end_time']);

        if ($type == 0) {
            $count = D('suppliers')->count();
        } else {
            $count = D('lining')->count();
        }
        if ($type == 0) {
            $suppliers_db = D('suppliers');
            if(!isset($post['action']) || $post['action']!="export") {
                import("ORG.Util.Page");
                $Page = new Page($count, $pageRows);
                $pageShow = $Page->show();
                $this->assign('pageShow', $pageShow);

                $suppliers_db->limit($Page->firstRow . ',' . $Page->listRows);
            }
            $suppliers_db->where($where);
            $list = $suppliers_db->select();
        } else {
            $lining_db = D('lining');
            if(!isset($post['action']) || $post['action']!="export") {
                import("ORG.Util.Page");
                $Page = new Page($count, $pageRows);
                $pageShow = $Page->show();
                $this->assign('pageShow', $pageShow);

                $lining_db->limit($Page->firstRow . ',' . $Page->listRows);
            }
            $lining_db->where($where);
            $list = $lining_db->select();
        }
        if((!empty($type) || $type==0) && isset($_REQUEST['type'])){
            $this->assign('type', $type);
        }else{
            $this->assign('type', "");
        }
        $inventory_db = D('inventory');
        foreach ($list as $key => $val) {
            $where['type'] = $type;
            if($type==0){
                $where['tid'] = $val['suppliers_id'];
            }else{
                $where['tid'] = $val['lining_id'];
            }
            $inventory = $inventory_db->where($where)->order('id DESC')->find();
            $list[$key]['inventory'] = $inventory;
        }
        if(isset($post['action']) && $post['action']=="export"){
            $this->suppliers_excel($list);
            exit;
        }
        $this->assign('list', $list);
        $this->assign('sort_by', $sort_by);
        $this->assign('order_by', $order_by);
        $this->display('suppliers_stats');
    }


    //用料统计
    public function inventory_stats()
    {
        $where = array();
        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }

        //order by
        if (isset($_REQUEST['sort_by']) && $_REQUEST['sort_by']) {
            $sort_by = $_REQUEST['sort_by'];
        } else {
            $sort_by = 'DESC';
        }

        if (isset($_REQUEST['order_by']) && $_REQUEST['order_by']) {
            $order_by = $_REQUEST['order_by'];
        } else {
            $order_by = 'id';
        }
        $post = $_REQUEST;
        if ($post['start_time'] && $post['end_time']) {
            $start_time = strtotime($post['start_time']);
            $end_time = strtotime($post['end_time']);
            $where['recordTime'] = array(array('egt', $start_time), array('lt', $end_time), 'and');
        } else {
            if ($post['start_time']) {
                $start_time = strtotime($post['start_time']);
                $where['recordTime'] = array('egt', $start_time);
            }
            if ($post['end_time']) {
                $end_time = strtotime($post['end_time']);
                $where['recordTime'] = array('lt', $end_time);
            }
        }
        $type = $_REQUEST['type'];

        if((!empty($type) || $type==0) && isset($_REQUEST['type'])){
            $where['type'] = $type;
            $this->assign('type', $type);
        }else{
            $where['type'] = array('lt',2);
            $this->assign('type', "");
        }
        $this->assign('start_time', $post['start_time']);
        $this->assign('end_time', $post['end_time']);

        $inventory_db = D('inventory');
        $count = $inventory_db->where($where)->count();
        if(!isset($post['action']) || $post['action']!="export") {
            import("ORG.Util.Page");
            $Page = new Page($count, $pageRows);
            $pageShow = $Page->show();
            $this->assign('pageShow', $pageShow);

            $inventory_db->limit($Page->firstRow . ',' . $Page->listRows);
        }
        $inventory_db->order($order_by . ' ' . $sort_by);
        $inventory_db->where($where);
        $inventoryList = $inventory_db->select();

        foreach ($inventoryList as $key => $val) {
            $order = D('orders')->where(array('id' => $val['order_id']))->find();
            if ($order) $inventoryList[$key]['orderTime'] = $order['start_time'];
            //面料 里布
            if ($val['type'] < 2) {
                if ($val['type'] == 0) {
                    $suppliers = D('suppliers')->where(array('suppliers_id' => $val['tid']))->find();
                } else {
                    $suppliers = D('lining')->where(array('lining_id' => $val['tid']))->find();
                }
            }
            $inventoryList[$key]['suppliers_name'] = $suppliers['suppliers_name'];
        }
        if(isset($post['action']) && $post['action']=="export"){
            $this->inventory_excel($inventoryList);
            exit;
        }

        $this->assign('inventoryList', $inventoryList);
        $this->assign('sort_by', $sort_by);
        $this->assign('order_by', $order_by);
        $this->display('inventory_stats');
    }


    /**
     * inventory_excel   库存导出
     * @param $inventoryList 需要导出的数据集合
     */
    private function suppliers_excel($inventoryList){
        foreach($inventoryList as $key=>$value){
            $inventory_var = array(
                '1' => $value['suppliers_name'],
                '2' => $value['inventory']['change'] == 0 ? $value['inventory']['before'] - $value['inventory']['amount'] : $value['inventory']['before'] + $value['inventory']['amount'],

            );
            $inventory_arr[] = $inventory_var;
        }
        import('COM.XmlExcel');
        $excel = new XmlExcel;
        $excel_title = array('面料编号','结余(米)');
        $excel->setSheetHead($excel_title);
        $excel->addRows($inventory_arr);
        $excel->setDefaultWidth(100);
        $excel->export('库存统计' . date('ymdHis'));
    }

    /**
     * inventory_excel   用料记录导出
     * @param $inventoryList 需要导出的数据集合
     */
    private function inventory_excel($inventoryList){
        foreach($inventoryList as $key=>$value){
            $inventory_var = array(
                '1' => $value['suppliers_name'],
                '2' => $value['order_sn'] ? $value['order_sn'] . '-' . $value['order_item_id'] : "",
                '3' => $value['pid'],
                '4' => $value['change'] == 0 ? $value['amount'] : 0,
                '5' => $value['change'] == 1 ? $value['amount'] : 0,
                '6' => $value['change'] == 0 ? $value['before'] - $value['amount'] : $value['before'] + $value['amount'],
                '7' => $value['orderTime'] > 0 ? date('Y-m-d H:i:s', $value['orderTime']) : '',
                '8' => date('Y-m-d H:i:s', $value['recordTime']),
                '9' => $value['remark'],
            );
            $inventory_arr[] = $inventory_var;
        }
        import('COM.XmlExcel');
        $excel = new XmlExcel;
        $excel_title = array('面料编号','订单ID', '产品id', '用料(米)', '增加(米)', '结余(米)', '下单时间'
        , '用料时间', '备注');
        $excel->setSheetHead($excel_title);
        $excel->addRows($inventory_arr);
        $excel->setDefaultWidth(100);
        $excel->export('用料记录统计' . date('ymdHis'));
    }
    //库存手动增加
    public function inventory_add()
    {
        $type = intval($_REQUEST['type']);
        $tid = intval($_REQUEST['tid']);

        if ($_POST['dosubmit']) {
            //面料第一次入口记录上架时间
            if ($type == 0 && $tid > 0) {
                $s_where = array(
                    'type' => $type,
                    'tid' => $tid,
                    'change' => 1,
                );
                $count = D('inventory')->where($s_where)->count();
                if ($count == 0) {
                    $editData['up_time'] = time();
                    D('suppliers')->where(array('suppliers_id' => $tid))->save($editData);
                }
            }
            //写入数据
            $post = $_POST;
            $res = SuppliersModel::inventoryAdd($post);

            //取缓存里的返回地址
            $goUrl = "";
            if ($type == 0) $goUrl = cookie('suppliers_list_nowPage');
            if ($type == 1) $goUrl = cookie('lining_list_nowPage');
            if ($type == 2) $goUrl = cookie('product_list_nowPage');
            if (!$goUrl) $goUrl = U('suppliers/suppliers_list');
            cookie('suppliers_list_nowPage', null);
            cookie('lining_list_nowPage', null);
            cookie('product_list_nowPage', null);
            $this->success('操作成功', $goUrl);
            //echo "<script>window.history.go(-2);</script>";
            exit;
        }

        $this->assign('type', $type);
        $this->assign('tid', $tid);
        $this->display('inventory_add');
    }

    //订单设置面料 里料数据
    public function set_inventory()
    {
        $order_item_id = intval($_REQUEST['order_item_id']);
        $order_items_db = D('orders_items');
        $order_item_info = $order_items_db->find($order_item_id);
        $order = M('orders');
        $order_item_info['order_sn'] = $order->where(array('id' => $order_item_info['order_id']))->getField('order_sn');

        if ($_POST['dosubmit']) {
            $post = $_POST;
            // echo '<pre />';
            // print_r($post);
            foreach ($post['tid'] as $key => $tid) {
                $addPost = array(
                    'type' => $post['type'][$key],
                    'tid' => $tid,
                    'order_sn' => $order_item_info['order_sn'],
                    'order_id' => $order_item_info['order_id'],
                    'order_item_id' => $order_item_info['id'],
                    'pid' => $order_item_info['product_id'],
                    'amount' => -$post['amount'][$key],
                );
                // echo '<pre />';
                // print_r($addPost);
                $res = SuppliersModel::inventoryAdd($addPost);
            }
            echo '<script stype="text/javascript" >window.opener=null;window.close();</script>';
            exit;
        }
        $this->assign('order_item_info', $order_item_info);

        //商品数据
        $product_db = D('product');
        $product_info = $product_db->where(array('id' => $order_item_info['product_id']))->find();
        $this->assign('product_info', $product_info);
        //面料
        $suppliers_db = D('suppliers');
        $suppliers_info = $suppliers_db->where(array('suppliers_id' => $product_info['suppliers_id']))->find();
        $suppliers_info['surplus'] = SuppliersModel::inventorySurplus(0, $suppliers_info['suppliers_id']);
        $this->assign('suppliers_info', $suppliers_info);
        //商品类型
        $orderfigure = OrderModel::orderPrintFigure($order_item_id);
        $this->assign('orderfigure', $orderfigure);

        $lining_key = 0;
        if ($product_info['model_id'] == 2) {
            $lining_key = 90;//两件套
        } elseif ($product_info['model_id'] == 14) {
            //$lining_key = 0;
        } elseif ($product_info['model_id'] == 18) {
            $lining_key = 111;//三件套
        } elseif ($product_info['model_id'] == 20) {
            $lining_key = 135;
        } elseif ($product_info['model_id'] == 21) {
            //$lining_key = 133;
        } elseif ($product_info['model_id'] == 1) {
            $lining_key = 69;
        } elseif ($product_info['model_id'] == 22) {
            $lining_key = 136;
        } elseif ($product_info['model_id'] == 23) {
            //$lining_key = 138;	//特俗礼服处理
        }
        if ($lining_key > 0) {
            $lining_db = D('lining');
            $lining_info = $lining_db->where(array('suppliers_name' => $orderfigure['attr_array'][$lining_key]['cn_attr_value_name']))->find();
            $lining_info['surplus'] = SuppliersModel::inventorySurplus(1, $lining_info['lining_id']);
            $this->assign('lining_info', $lining_info);
        }

        $this->display('set_inventory');
    }

    //显示库存
    public function inventorySurplus()
    {
        $type = $_REQUEST['type'];
        $tid = $_REQUEST['tid'];
        echo SuppliersModel::inventorySurplus($type, $tid);
    }

    //设置进货
    public function setting_stock()
    {
        $tid = intval($_REQUEST['id']);
        $stock = intval($_REQUEST['stock']);
        $type = intval($_REQUEST['type']);
        if ($type == 0) {
            D('suppliers')->where(array('suppliers_id' => $tid))->save(array('stock' => $stock));
        } else if ($type == 1) {
            D('lining')->where(array('lining_id' => $tid))->save(array('stock' => $stock));
        } else if ($type == 2) {
            D('product')->where('id=' . $tid)->save(array('stock' => $stock));
        }
    }
}